#include "basket.h"

Basket::Basket()
{
    rows = new QList<QPair<Session*, QList<bool>* > >();
    sessionRows = new Qlist<QPair<Session*, QStringList> >();
}

void Basket::addPage(QString page)
{
    pages.append(page);
}

void Basket::addSession(Session *session)
{
    //qDebug() << "New session in basket!";

    QList<bool> *values = new QList<bool>();

    for(int i = 0; i < pages.size(); ++i)
    {
        QString currentPage = pages.at(i);

        if(session->getPages().indexOf(currentPage) == -1)
        {
            // false!
            values->append(false);
        }
        else
        {
            // true!
            values->append(true);
        }
    }

    // And append to list with rest rows
    QPair<Session*, QList<bool>* > pair;
    pair.first = session;
    pair.second = values;

    rows->append(pair);
}

void Basket::addSessionClustering(Session *session)
{
    //
}

void Basket::saveBasketAsArff(QString filename)
{
    QFile file(filename);
    file.open(QIODevice::WriteOnly);

    QTextStream stream(&file);
    QPair<Session*, QList<bool>* >  currentRow;

    // Write file header
    stream << "@relation basket-data-final\n\n";

    // Write data types
    for(int i = 0; i < pages.size(); ++i)
        stream << "@attribute '" + pages.at(i) + "' { t}\n";

    stream << "\n\n@data\n\n";

    for(int i = 0; i < rows->size(); ++i)
    {
        currentRow = rows->at(i);

        QString row = "";
        for(int j = 0; j < currentRow.second->size(); ++j)
        {
            if(currentRow.second->at(j) == true)
            {
                row += "t,";
            }
            else
            {
                row += "?,";
            }
        }

        // Remove last comma
        row.remove(row.length()-1, 1);
        row += "\n";
        stream << row;
    }

    file.close();
}

void Basket::saveBasketForSessionsClusteringAsArff(QString filename)
{
    //
}

QStringList Basket::getPages()
{
    return pages;
}

QList<QPair<Session*, QList<bool>* > > *Basket::getRows()
{
    return rows;
}

void Basket::debug()
{
    qDebug() << "Preview content of basket!";

    // Show header of basket
    QString header = "";
    for(int i = 0; i < pages.size(); ++i)
    {
        header += pages.at(i) + " ";
    }

    qDebug() << header;

    for(int i = 0; i < rows->size(); ++i)
    {
        qDebug() << rows->at(i).first->getUserName() << rows->at(i).first->getHost() << *(rows->at(i).second);
    }
}
